<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								客户跟进记录
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- 							<el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="跟进客户" prop="customerNames">
									<el-select :readonly="route.query.id" @clear="selectClear('customerName')"
										v-model="formData.customerNames"
										@change="(value:any)=>selectChange(value,'customerNames')" multiple
										ref="customerNames" clearable>
										<el-option v-for="item in customerNameOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="customerNameOption[customerNameIndex]?.color">
															<component
																:is="customerNameOption[customerNameIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{customerNameOption[customerNameIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="本次跟进日期" prop="followUpDate">
									<el-date-picker placeholder="请选择" style="width:100%;"
										v-model="formData.followUpDate" type="date" />
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-form-item label="跟进人" prop="followUpPerson">
							<el-input v-model="formData.followUpPerson" readonly type="text" clearable></el-input>
						</el-form-item>
						<el-form-item label="跟进内容" prop="followUpContent">
							<el-input placeholder="请填写" v-model="formData.followUpContent" type="textarea"
								clearable></el-input>
						</el-form-item>
						<el-form-item label="位置" prop="location">
							<el-input type="text" clearable v-model="formData.location">
								<template #prefix>
									<el-button size="small" text :icon="Position" @click="geolocations">
									</el-button>
									<el-icon class="is-loading" v-if="formData.loading">
										<svg class="circular" viewBox="-10, -10, 50, 50">
											<path class="path" d="
										            M 30 15
										            L 28 17
										            M 25.61 25.61
										            A 15 15, 0, 0, 1, 15 30
										            A 15 15, 0, 1, 1, 27.99 7.5
										            L 15 15
										          " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)" />
										</svg>
									</el-icon>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="图片" prop="image">
							<el-input readonly clearable>
								<template #prefix>
									<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
										:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
										:limit="1">
										<el-button v-if="!formData.image" text :icon="UploadFilled">
											上传图片
										</el-button>
										<img v-else style="width: 20px;height: 20px;margin: 10px auto;"
											:src="formData.image" />
									</el-upload>
								</template>
							</el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ref, onMounted, reactive, shallowRef } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import { UploadFilled, ArrowDown, UserFilled, Plus, Position } from '@element-plus/icons-vue';
	import { ElLoading } from 'element-plus';
	import request from '../../../utils/request';
	import { ElMessage, FormInstance, UploadProps } from 'element-plus';
	import { colors, findIndexByLabel, isEmpty, mergeObjects, removeEmptyProperties } from '../../../utils/index';
	import { formatDate } from '../../../utils/date';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	import { useSelect } from '../../../utils/mixins';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	// 表单
	const formData = ref({
		customerName: [],
		customerNames: [],
		followUpDate: '',
		followUpPerson: '',
		followUpContent: '',
		location: '',
		loading: false,
		image: ''
	});
	//
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
	});
	//

	const customerNameOption = ref([]);
	//
	//
	const rules = reactive({
		customerNames: [{ required: true, message: '跟进客户必选！', trigger: ['blur', 'change'] }],
		followUpDate: [{ required: true, message: '本次跟进日期必选！', trigger: ['blur', 'change'] }],
		followUpPerson: [{ required: true, message: '跟进人必填！', trigger: ['blur', 'change'] }],
		followUpContent: [{ required: true, message: '跟进内容必填！', trigger: ['blur', 'change'] }],
		location: [],
		image: []
	});
	//
	onMounted(() => {
		// getCustomer();
	});
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getCustomer();
			//
			if (result) {
				getPageList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		sourceIndex.value = -1;
		customerNameIndex.value = -1;
		customerNameOption.value = [];
		//清空url参数
		router.push({ query: {} });
	}
	//
	const getCustomer = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.followUpPerson = decodedToken?.username;
			//
			return true;
		}
		const result = await request({
			url: '/login/selectFollowUp',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getCustomer--->', result);
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//
	const customerNames = ref(null);
	//
	const customerNameIndex = ref(-1);
	const sourceIndex = ref(-1);
	//
	//改变
	const selectChange = (value : Array<any>, type : string) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'customerNames', //哪一个下拉框，根据ref
			option: customerNameOption, //下拉列表选项
			indexVar: customerNameIndex, //当前选中项
			idVar: 'customerName', //当前id值
			blurRef: customerNames, //ref
		}];
		//
		handSelectChange(formData, typeList, value, type);
	}
	//
	//获取客户信息
	const getPageList = async () => {
		// const loading = ElLoading.service({
		// 	lock: true,
		// 	text: '加载中...',
		// 	background: 'rgba(0, 0, 0, 0.5)',
		// });
		const result = await request({
			url: '/login/selectCustomerAll',
			params: pageData.value
		});
		//
		customerNameOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			customerNameOption.value.push({
				label: `${item.customerName}（${item.customerRating}）${item.billingMethod}`,
				value: item.customerName,
				icon: UserFilled,
				color: '#82b51b'
			});
		});
		customerNameOption.value.forEach((item : any, key : number) => {
			if (formData.value.customerName === item.value) {
				formData.value.customerNames = [item.value];
				customerNameIndex.value = key;
			}
		});
		// loading.close();
		return true;
	};
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let type = '';
				if (!route.query.id) {
					type = '/saveFollowUp';
				} else {
					type = '/updateFollowUp';
				}
				//
				const result = await request({
					url: '/login' + type,
					data: formData.value,
					method: 'post'
				});
				vFormRef.value.resetFields();
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//
	const onSuccess = (response : { t : string; }, uploadFile : any) => {
		console.log('response--->', response);
		formData.value.image = response.t;
	}
	//获取位置
	const geolocations = async () => {
		formData.value.loading = true;
		const { coords: { latitude, longitude } } = await geolocation();
		//
		const result = await request({
			url: 'http://localhost:3000/api/ip/getIpInfoPlus',
			params: { latitude, longitude }
		});
		console.log('geolocations --->', result);
		const { ad_info, address_reference: { town } } = result.data.result;
		const location = `${ad_info.nation}-${ad_info.province}-${ad_info.city} ${ad_info.district}${town.title}${town._dir_desc}`;
		// if (formData.value.location) {
		console.log('location --->', location);
		formData.value.location = location;
		formData.value.loading = false;
		// }
	}
	//获取经纬度信息
	const geolocation = () : Promise<any> => {
		return new Promise((resolve, reject) => {
			navigator.geolocation.getCurrentPosition(
				(result) => {
					console.log('result--->', result);
					resolve(result);
				},
				(error) => {
					switch (error.code) {
						// 处理错误
					}
					reject(error);
				},
				{
					timeout: 5000,
				}
			);
		});
	}

	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-upload-list--text {
		display: none;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>